# -*- coding: UTF-8 -*-
import os
import json
import optparse
from handle_path import config_path

parser = optparse.OptionParser()
parser.add_option('-e', dest='deepfos_host', type='string', default='')
parser.add_option("-a", dest='account_host', type='string', default='')
parser.add_option('-u', dest='user', type='string', default=",")
parser.add_option('-n', dest='db_name', type='string', default=",,,,")
parser.add_option('-d', dest='database', type='string', default=",3306,,")
# 连接账户中心数据库信息，默认None取database的连接信息
parser.add_option('-b', dest='account_db', type='string', default=None)
# 自动创建标识，true为创建空间和app,false为不创建则需要填写space和appid
parser.add_option('-c', dest='auto_create', type="string", default=True)
parser.add_option('-s', dest='space_id', type='string', default='')
parser.add_option('-p', dest='app_id', type='string', default='')
option, args = parser.parse_args()


def update_param():
    # 用户信息
    user_info = option.user.split(",")
    # 数据库名
    db_names = option.db_name.split(",")
    # 数据库连接信息
    database_info = option.database.split(",")
    if str(option.auto_create).lower() == "true":
        option.auto_create = True
    elif str(option.auto_create).lower() == "false":
        option.auto_create = False
    # 当自动创建标识为false，space和app是必传的
    if not option.auto_create:
        assert option.space_id, "space_id未传"
        assert option.app_id, "app_id未传"
    config_data = {
        "deepfos_host": option.deepfos_host,
        "account_host": option.account_host,
        "user": {
            "username": user_info[0],
            "password": user_info[1]
        },
        "db_name": {
            "system": db_names[0],  # 操作系统数据库名
            "app": db_names[1],  # app数据库名
            "account": db_names[2],  # 账户中心数据库名
            "pipeline": db_names[3],  # 数据流数据库名
            "calculation": db_names[4]  # 计算流数据库名
        },
        "database": {
            "host": database_info[0],
            "port": int(database_info[1]),
            "user": database_info[2],
            "passwd": database_info[3]
        },
        "auto_create": option.auto_create,
        "space_id": option.space_id,
        "app_id": option.app_id
    }
    # 账户中心数据库连接信息
    if option.account_db:
        account_db = option.account_db.split(",")
        config_data.update({
            "account_db": {
                "host": account_db[0],
                "port": int(account_db[1]),
                "user": account_db[2],
                "passwd": account_db[3]
            }
        })
    file_path = os.path.join(config_path, 'initialization.json')
    with open(file_path, 'w', encoding='utf8') as f:
        json.dump(config_data, f, ensure_ascii=False)


if __name__ == '__main__':
    update_param()
